<!--3	季度交通违法情况通报-->
<template>
  <Layout>
    <Form ref="form1" :model="dataToQuery" :label-width="120">
      <Row class="query-form">
        <Col span="8">
          <FormItem label="年度：" prop="year">
            <DatePicker class="query-form-el" type="year" placeholder="请选择年度" v-model="dataToQuery.year1"
                        :clearable="false"
                        @on-change="()=>{if(dataToQuery.year1 instanceof Date){dataToQuery.year = dataToQuery.year1.getFullYear().toString()}}"></DatePicker>
          </FormItem>
        </Col>
        <Col span="16">
          <Button @click="reset1" class="ivu-btn-reset">重置</Button>
          <Button type="primary" class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
    </Form>
    <Table ref='table' :height="tableHeight" no-data-text="没有查询到相关数据!" @on-selection-change='getSelectRows'
           :loading='pageStatus.loading'
           border :columns="columns1" :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page style="float: right" :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray" show-total show-sizer
              show-elevator/>
      </Col>
    </Row>

    <Modal title="交通考核汇总" :transfer=false :mask-closable="false"
           v-model="dialogRecordShow"  :width=800 :styles="{maxHeight:'700px'}"
           class-name='limit-height-dialog'>
      <Form ref="form1datacopy" :model="form1datacopy" label-position="top">
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="24">
            <FormItem label="年份：" prop="year">
              <Input type="text" readonly v-model="form1datacopy.year"></Input>
            </FormItem>
          </Col>
        </Row>
        <Row type="flex" justify="space-around" class="code-row-bg">
          <Col span="24">
            <FormItem label="附件：" prop="year">
              <div>
                <Upload ref="upload"
                        :before-upload="beforeUpload"
                        :show-upload-list="true"
                        :max-size="10240"
                        type="drag"
                        action="//jsonplaceholder.typicode.com/posts/">
                  <div style="padding: 10px">
                    <Icon type="ios-cloud-upload" size="45" style="color: #3399ff"></Icon>
                    <p>点击将文件拖拽到这里上传</p>
                    <span style="font-size:8px;color: #797a64">仅支持上传单个excel </span>
                  </div>
                </Upload>
              </div>
              <div v-if="fileTrue">
                <a>{{ file.name }}</a>
                <Button type="text" icon="md-trash" @click="deleteFile(file)" style="margin-left: 5px;margin-bottom: 3px"/>
              </div>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button type="primary" class='ivu-btn-save' :loading="buttonLoading"   @click="postFile">确定</Button>
        <Button type="primary" class='ivu-btn-cancel' @click="dialogRecordShow = false">取消</Button>
      </div>
    </Modal>
  </Layout>
</template>

<script>
import {Api} from '@/api/index.js'
import {formatDate} from '@/tools/index'

var cascaderDom = () => import('@/components/cascader-dom.vue');
import pageCommonFunction from '@/components/pageCommonFunction.js'
import {sessionStorage, cookie} from '@/common/cacheUtils.js';

export default {
  components: {cascaderDom},
  data() {
    return {
      ...this.createCommonDataField(),
      buttonLoading:false,
      dialogRecordShow:false,
      form1datacopy:{},
      columns1: [
        {title: '序号', width: 70, fixed: 'left', align: 'center', render: this.indexColumnsRender},
        {key: 'year', title: '年份', align: 'center', minWidth: 120,},
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            let flag = false;
            console.log(params.row.uploadList)
            if(params.row.uploadList != undefined && params.row.uploadList.length > 0)
              flag = true;
            console.log(flag)
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:!flag?'':'#c5c8ce',
                  pointerEvents:!flag?'':'none'
                },
                on: {
                  click: () => {
                    this.exportTemplateDatas(params.row.year);
                  }
                }
              }, '导出'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.showRecordDialog(params.row);
                  }
                }
              }, '上传'),
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  color:flag?'':'#c5c8ce',
                  pointerEvents:flag?'':'none'
                },
                on: {
                  click: () => {
                    this.downloadFile(params.row);
                  }
                }
              }, '下载')
            ])
          }
        }
      ],
      ruleCustom: {
        yearDate: [{required: true, message: '请选择年份', trigger: 'change', type: 'date'}],
        createUserName: [{required: true, message: '请填写填报人', trigger: 'change',}],
        createDate: [{required: true, message: '请填写填报时间', trigger: 'change', type: 'date'}],
        idFiles: [{
          validator: (rule, value, callback) => {
            if (this.dataToView.idFiles.length < 1) {
              callback('附件必须上传')
            } else {
              callback()
            }
          },
          required: true,
          trigger: 'change'
        }]
      },
      fileTrue:false,
      file:{},
      currentRow:{},
      tableHeight: 10,
      dictMap: {},
      punishment: false,
      penaltyAmount: true,
      // api
      queryUrl: Api.trafficBreakRawListByTime,
      exportUrl: Api.exportSaTraff.replace('{{table}}', 'violationNotification'),
      deleteUrl: Api.deleteSaTraff.replace('{{table}}', 'violationNotification'),
      getUrl: Api.getSaTraff.replace('{{table}}', 'violationNotification'),
      updateUrl: Api.updateSaTraff.replace('{{table}}', 'violationNotification'),
      saveUrl: Api.saveSaTraff.replace('{{table}}', 'violationNotification'),
      uploadUrl: Api.uploadSaTraff.replace('{{table}}', 'violationNotification'),
      currentUser: JSON.parse(sessionStorage('userId').get('userId')),
    }
  },
  async mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 100;
    this.dataToQuery.year1 = new Date()
    this.dataToQuery.year = new Date().getFullYear().toString()
    this.query();
  },
  methods: {
    ...pageCommonFunction,
    beforeEditDialogOpen(data) {
      let year = data.row.year + '-01-01';
      data.row.yearDate = new Date(Date.parse(year.replace(/-/g, "/")));
    },
    deleteData(params) {
      this.deleteDateAjax(params);
    },
    reset1() {
      this.dataToQuery = {
        year1: new Date(),
        year: new Date().getFullYear().toString()
      };
      this.pagedata.currentPage = 1
      this.query()
    },
    query() {
      this.pageStatus.loading = true;
      let url = Api.trafficBreakRawListByYear;
      this.$http.get(url, {
        params: this.dataToQuery
      }).then((res) => {
        this.pageStatus.loading = false;
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        this.dataTable.forEach(item=>{
          this.getFile(item);
        })
      }).catch(e => {
        this.$Message.error("数据获取失败")
      })
    },
    showRecordDialog(item){
      this.dialogRecordShow = true;
      this.form1datacopy = item;
      this.fileTrue = false;
      this.currentRow = item;
      if(item.uploadList.length > 0){
        this.fileTrue = true;
        this.file = item.uploadList[0]
        this.file.name = this.file.fileName
      }
    },
    beforeUpload(file){
      if(this.fileTrue){
        this.$Message.error('已存在附件.');
        return false;
      }
      this.file = file;
      this.fileTrue = true
      return false;
    },
    getFile(item){
      var uploadImgUrl = Api.uploadPTWFiles + '/' + item.year + '/files/examine';
      this.$http.get(uploadImgUrl, {
        params: {},
      }).then((res) => {
        console.log(res);
        if (res.data.result == "success") {
          this.$set(item,"uploadList",res.data.data);
        }
      })
    },
    deleteFile(){
      if(this.file.id != undefined) {
        let url = this.fileUrl + '/file/' + this.file.id;
        this.$http.delete(url).then((res) => {
          this.file = {}
          this.fileTrue = false;
        })
      }else{
        this.file = {}
        this.fileTrue = false;
      }
    },
    postFile(){
      if(this.fileTrue) {
        this.buttonLoading = true;
        let formData = new FormData();
        formData.append("files", this.file);
        this.$http.post(Api.uploadPTWFiles + '/' + this.currentRow.year + '/files/examine', formData).then((res) => {
          if (res.data.result == "success") {
            this.$Message.success("保存成功");
            this.buttonLoading = false;
            this.dialogRecordShow = false;
            this.getFile(this.currentRow);
          } else {
            this.buttonLoading = false;
            this.$Message.error("附件上传失败");
            this.dialogRecordShow = false;
          }
        }).catch(e => {
          console.log(e);
          this.$Message.error("附件上传失败");
        })
      }else{
        this.$set(this.currentRow,"uploadList",[]);
        this.dialogRecordShow = false;
      }
    },
    downloadFile(item){
      if(item.uploadList.length > 0) {
        this.$http.get(Api.uploadPTWFiles + '/file/' + item.uploadList[0].id, {
          responseType: 'blob'      //告诉服务器我们需要的响应格式
        }).then((res) => {
          const aLink = document.createElement("a");
          let blob = new Blob([res.data], {
            type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
          });
          aLink.href = URL.createObjectURL(blob)
          aLink.download = item.uploadList[0].fileName //标题
          aLink.click()
          document.body.appendChild(aLink)
        })
      }
    },
    exportTemplateDatas(year) {
      let data = {
        year: year
      };
      let _this = this;
      this.buttonLoading = true;
      let url = Api.exportTrafficExamine;
      this.$http.get(url, {
        params: data, responseType: 'blob',
      }).then((res) => {
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.body.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        aLink.download = "交通考核汇总.xlsx" //标题
        aLink.click()
        this.buttonLoading = false;
        this.exportModal = false;
        document.body.appendChild(aLink)
      })
    },
  },
  watch: {},
}
</script>

<style lang='css' scoped>
.ivu-form-item {
  padding-right: 20px;
}

.query-form-el, .ivu-date-picker, .ivu-input-wrapper {
  width: 100%;
}

</style>
